<?php

namespace app\api\controller;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Api;
use app\common\func\Constant;
use app\common\func\Lib;
use app\common\func\Tools;
use app\common\func\WeChat;
use app\common\model\Address;
use app\common\model\Admin;
use app\common\model\Article;
use app\common\model\GiftOrder;
use app\common\model\ServiceLog;
use app\common\model\TerminalApply;
use app\common\model\TerminalDetail;
use app\common\model\UserCard;
use app\common\model\User;
use fast\Random;
use fast\Tree;
use think\Config;
use think\Db;
use think\Exception;
use EasyWeChat\Factory;

/**
 * 首页接口
 */
class V1 extends Api
{
    protected $noNeedLogin = ['getProductList', 'getBanner', 'getAgree', 'getReferrer', 'getContent', 'getQuestion', 'getReceiveType', 'sendSms', 'test', 'test1'];
    protected $noNeedRight = ['*'];

    public function getUserInfo(){
        $this->success("用户信息",Lib::getUserCard($this->auth->id));
    }

    public function test1()
    {
        $wx = new WeChat();
        var_dump($wx->getUser("opFhH6lakZrBPLz4o1B1evlSLoyg"));
    }

    public function confirmApply()
    {
        $applyId = $this->request->post('apply_id');

        $apply = Lib::getApply($applyId);
        if (!$apply) {
            $this->error("申请记录不存在");
        }

        $apply->confirm_time = time();
        $result = $apply->save();

        if ($result) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function indexCount()
    {
        list($msg, $count) = Lib::getTerminalCount($this->auth->is_typs, $this->auth->admin_id);
        $arr = [
            "paramA" => ["title" => "申领记录", "total" => Lib::getApplyCount($this->auth->is_typs, $this->auth->admin_id)],
            "paramB" => ["title" => $msg, "total" => $count],
        ];

        $this->success("首页数据", $arr);
    }

    public function delAdmin()
    {
        $adminId = $this->request->post('admin_id');

        $admin = Admin::get($adminId);
        if (!$admin) {
            $this->error("用户不存在");
        }

        $admin->status = "hidden";
        $result = $admin->save();
        if ($result) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function getAdminList()
    {
        $group = Tools::getGroupTree(Constant::$masterGroup, 4);
        $list = Db::name("admin")->alias("a")
            ->join("auth_group_access b", "a.id = b.uid", "left")
            ->where(['group_id' => ['in', $group], "status" => "normal"])
            ->field("a.id,a.nickname,a.avatar,a.mobile")
            ->select();
        $this->success("业务员后台列表", $list);
    }

    public function showQr()
    {
        $adminId = $this->request->post('admin_id');

        $url = "";
        $admin = Admin::get($adminId);
        $access = AuthGroupAccess::where(['uid' => $adminId])->find();
        if (!$admin || !$access) {
            $this->error("用户不存在");
        }
        if ($admin->qr_url) {
            $url = $admin->qr_url;
        } else {
            $text = [
                "group_id" => $access->group_id,
                "admin_id" => $adminId,
                "name" => $admin->nickname,
            ];

            $params = ["text" => Constant::$kfUrl . "?" . http_build_query($text)];
            $qrCode = \addons\qrcode\library\Service::qrcode($params);
            $config = get_addon_config('qrcode');
            $qrcodePath = './uploads/qrcode/user/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                $qrCode->writeFile($filePath);

                $url = substr($filePath, 1);
                $admin->qr_url = $url;
                $admin->save();
            }
        }
        $this->success("身份二维码", $url);
    }

    public function createAdmin()
    {
        $groupId = $this->request->post('group_id', 9);
        $username = $this->request->post('username');
        $mobile = $this->request->post('mobile');
        $nickname = $this->request->post('nickname');
        $password = $this->request->post('password');

        if (!$groupId || !$username || !$mobile || !$nickname || !$password) {
            $this->error("缺少参数");
        }

        $adminMobile = Admin::where(['mobile' => $mobile])->find();
        if ($adminMobile) {
            $this->error("该手机号已注册");
        }

        $salt = Random::alnum();
        $avatar = '/assets/img/avatar.png'; //设置新管理员默认头像。

        $result = false;
        Db::startTrans();
        try {
            $admin = new Admin();
            $admin->username = $username;
            $admin->mobile = $mobile;
            $admin->nickname = $nickname;
            $admin->salt = $salt;
            $admin->avatar = $avatar;
            $admin->password = md5(md5($password) . $salt);
            $admin->email = $mobile . "@qq.com";
            $admin->save();

            $access = new AuthGroupAccess();
            $access->save(['uid' => $admin->id, 'group_id' => $groupId]);

            $result = true;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }

        if ($result) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function getGroup()
    {
        $groupList = collection(AuthGroup::where(['status' => 'normal'])->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        foreach ($result as $k => $v) {
            if ($k >= 1) {
                $groupdata[$v['id']] = $v['name'];
            }
        }
        $this->success("角色组", $groupdata);
    }

    public function getTerminalApplyDetail()
    {
        $applyId = $this->request->post('apply_id');

        $this->success("详情", Lib::getTerminalApplyDetail($applyId));
    }

    public function checkApply()
    {
        $applyId = $this->request->post('apply_id');
        $type = $this->request->post('type');

        $terminalApply = Lib::getTerminalApplyById($applyId);
        if (!$terminalApply) {
            $this->error("申请不存在");
        }
        if (!in_array($type, [0, 2])) {
            $this->error("类型错误");
        }

        $terminalApply->status = $type;
        $result = $terminalApply->save();
        if ($result) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function saveTerminal()
    {
        $sn = $this->request->post('sn/a');
        $applyId = $this->request->post('apply_id');

        if (count($sn) == 0) {
            $this->error("请添加终端");
        }

        $apply = Lib::getApply($applyId);
        if (!$apply) {
            $this->error("申请记录不存在");
        }

        $data = [];
        foreach ($sn as $key => $val) {
            $terminal = Lib::getTerminal($val);
            if (!$terminal || $terminal->user_id > 0) {
                $this->error("终端【" . $val . "】不存在或已绑定");
            }

            $data[] = [
                "apply_id" => $applyId,
                "sn" => $val
            ];
        }

        $result = false;
        Db::startTrans();
        try {
            $detail = new TerminalDetail();
            $result = $detail->saveAll($data);

            $apply->status = 3;
            $apply->save();

            $result = true;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }

        if ($result) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function divideSale()
    {
        $applyId = $this->request->post('apply_id');
        $userId = $this->request->post('user_id');

        $apply = Lib::getApply($applyId);
        if (!$apply) {
            $this->error("申请记录不存在");
        }

        $user = Lib::getUserById($userId);
        if (!$user || $user->admin_id == 0) {
            $this->error("用户不存在");
        }

        $apply->admin_id = $user->admin_id;
        $result = $apply->save();

        if ($result) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function getSaleList()
    {
        $this->success("业务员", Lib::getSaleList());
    }

    public function bindTerminal()
    {
        $applyId = $this->request->post('apply_id');
        $sn = $this->request->post('sn');

        $apply = Lib::getApply($applyId);
        if (!$apply) {
            $this->error("申请记录不存在");
        }

        $terminalApply = Lib::getTerminalSale($sn);
        $detail = Lib::getTerminalDetail($terminalApply['id'], $sn);
        if (!$terminalApply || !$detail) {
            $this->error("终端不属于业务员！");
        }

        $terminal = Lib::getTerminal($sn);
        if (!$terminal || $terminal->user_id > 0) {
            $this->error("终端不存在或已绑定");
        }

        $result = false;
        Db::startTrans();
        try {
            $apply->product_id = $terminal->product_id;
            $apply->sn = $sn;
            $apply->status = 4;
            $apply->save();

            $terminal->user_id = $apply->user_id;
            $terminal->save();

            $detail->status = 2;
            $detail->save();

            $result = true;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }

        if ($result) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function saveTerminalApply()
    {
        $productId = $this->request->post('product_id');
        $number = $this->request->post('number');

        $apply = new TerminalApply();
        $apply->admin_id = $this->auth->admin_id;
        $apply->product_id = $productId;
        $apply->number = $number;
        $result = $apply->save();

        if ($result) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function getTerminalApplyList()
    {
        $this->success("申请列表", Lib::getTerminalApplyList($this->auth));
    }

    // 获取收货类型
    public function getReceiveType()
    {
        $data = [
            ["id" => 1, "name" => "到店"],
            ["id" => 2, "name" => "快递"]
        ];
        $this->success("收货类型", $data);
    }

    public function editApply()
    {
        $id = $this->request->post('id');
        $addressId = $this->request->post('address_id');

        $apply = Lib::getApply($id);
        $address = Lib::getUserAddressById($addressId);

        if (!$apply || !$address) {
            $this->error("参数错误!");
        }

        $apply->name = $address->name;
        $apply->phone = $address->mobile;
        $apply->address = $address->province . $address->city . $address->district . $address->address;
        $result = $apply->save();

        if ($result) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function saveOrder()
    {
        $sn = $this->request->post('sn');
        $type = $this->request->post('type');
        $giftId = $this->request->post('gift_id');
        $province = $this->request->post('province');
        $city = $this->request->post('city');
        $district = $this->request->post('district');
        $address = $this->request->post('address');
        $flowMoney = $this->request->post('flow');

        if (!$sn) {
            $this->error("缺少参数！");
        }

        $giftOrder = Lib::getGiftOrderBySn($sn);
        if ($giftOrder) {
            $this->error("该终端已申请！");
        }

        $result = false;
        $msg = "";
        Db::startTrans();
        try {
            $order = Tools::saveOrder($this->auth->id, $giftId, $sn, $province, $city, $district, $address);
            if ($order == false) {
                \exception("订单创建失败");
            }
            $howMany = Lib::getFlowRewardHowMany($sn);
            $flow = Lib::getFlowBySn($sn);

            if (!$howMany && $flow) {
                if (in_array($type, [1, 2])) {
                    $pay = Tools::pay($sn, $this->auth->id, $flowMoney);
                    if ($pay['code'] == 0) {
                        \exception($pay['msg']);
                    }

                    $order->status = 2;
                    $order->save();
                } elseif ($type == 3) {
                    $order->status = 2;
                    $order->save();
                } else {
                    \exception("申请类型不存在");
                }
            }

            $result = true;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $msg = $e->getMessage();
        }

        if ($result) {
            $this->success("保存成功");
        } else {
            $this->error("打款失败：" . $msg);
        }
    }

    public function getSnInfo()
    {
        $sn = $this->request->post('sn');

        $info = Db::name("terminal")->alias("t")
            ->join("product p", "t.product_id = p.id", "left")
            ->join("product_apply a", "t.sn = a.sn", "left")
            ->where(['t.sn' => $sn, "t.user_id" => $this->auth->id, "a.status" => ['>', 0]])
            ->field("p.*,t.sn,a.type")
            ->find();
        $this->success("信息", $info);
    }

    public function getGiftSn()
    {
        $sn = GiftOrder::where(['status' => ['>', 1], "user_id" => $this->auth->id])->column("sn");
        $list = Db::name("terminal")->alias("t")
            ->join("product p", "t.product_id = p.id", "left")
            ->where(['sn' => ['not in', $sn], "user_id" => $this->auth->id])
            ->field("p.*,t.sn")
            ->select();
        $this->success("列表", $list);
    }

    public function getGiftList()
    {
        $type = $this->request->post('type');

        $this->success("礼品列表", Lib::getGift($type));
    }

    public function saveScore()
    {
        $serviceId = $this->request->post('id');
        $tip = $this->request->post('tip/a');
        $score = $this->request->post('score');
        $remark = $this->request->post('remark');

        $service = Lib::getService($serviceId);
        $service->tips = implode(",", $tip);
        $service->score = $score;
        $service->remark = $remark;
        $result = $service->save();

        if ($result) {
            $this->success("保存成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function getService()
    {
        $serviceId = $this->request->post('id');

        $this->success("评价信息", Lib::getService($serviceId));
    }

    public function saveQuestion()
    {
        $sn = $this->request->post('sn');
        $tip = $this->request->post('tip/a');
        $remark = $this->request->post('remark');

        if (!$sn) {
            $this->error("缺少参数");
        }

        $service = new ServiceLog();
        $service->sn = $sn;
        $service->question_id = implode(",", $tip);
        $service->question_content = $remark;
        $result = $service->save();

        if ($result) {
            $this->success("保存成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function getQuestion()
    {
        $type = $this->request->post('type');

        $this->success("问题列表", Lib::getQuestions($type));
    }

    public function getContent()
    {
        $this->success("用户", [
            "about" => Article::get(2),
            "user" => Article::get(1),
            "gets" => Article::get(3),
            "privacy" => Article::get(4),
            "cooperation" => Article::get(5)
        ]);
    }

    public function saveFlowReward()
    {
        $flowId = $this->request->post('flow_id');
        $type = $this->request->post('type');

        $flow = Lib::getFlow($flowId);
        if (!$flow) {
            $this->error("未查询到流量费信息");
        }

        $result = false;
        try {
            if ($type == 1) { //兑换余额
                $arr = [
                    "uid" => $this->auth->id, // 用户ID
                    "typs" => "LLK", // 变更类型
                    "isChg" => "1", // 1 收入 2 支出
                    "remark" => "流量费",    // 备注
                    "chgAmt" => $flow->flow_money,    // 变更金额
                ];

                \app\common\controller\Balance::instance()->changeOpera($arr);

                $flow->status = 1;
                $flow->save();

                $result = true;
            } elseif ($type == 2) { //兑换礼品
                //TODO
            }
        } catch (\Exception $e) {
        }

        if ($result) {
            $this->success("操作成功！");
        } else {
            $this->error("操作失败！");
        }
    }

    public function getFlowInfo()
    {
        $flowId = $this->request->post('id');

        $flowInfo = Lib::getFlowInfo($flowId);
        if (!$flowInfo) {
            $this->success("流量卡信息", []);
        }

        $this->success("流量卡信息", ["flow" => $flowInfo, "type" => Constant::$flowType]);
    }

    public function cancelApply()
    {
        $applyId = $this->request->post('id');

        $apply = Lib::getApplyByUser($this->auth->id, $applyId);
        if (!$apply) {
            $this->error("缺少参数！");
        }
        $apply->status = 0;
        $result = $apply->save();

        if ($result) {
            \app\data\controller\Apply::instance()->cancel_update_status($this->auth->id, $applyId);
            $this->success("取消成功");
        } else {
            $this->error("取消失败！");
        }
    }

    public function getApplyList()
    {
        $this->success("申请列表", Lib::getApplyList($this->auth->id));
    }

    public function getTranDetails()
    {
        $timeType = $this->request->post('time_type');

        $terminals = Lib::getUserTerminal($this->auth->id);

        $list = [];

        if (count($terminals) > 0) {
            foreach ($terminals as $key => $val) {
                $list = array_merge($list, Lib::getTranDetails($val['sn'], $val['table'], $timeType));
            }
        }

        $this->success("交易详情", $list);
    }

    public function getAddress()
    {
        $this->success("收货地址", Lib::getUserAddressByUser($this->auth->id));
    }

    public function getBanner()
    {
        $this->success("banner", Lib::getBannerList());
    }

    public function getIndexData()
    {
        $terminals = Lib::getUserTerminal($this->auth->id);

        $today = 0;
        $month = 0;
        $lastMonth = 0;
        $todayDate = date("Y-m-d");
        $monthDate = date("Y-m");
        $lastMonthDate = date("Y-m", strtotime("-1 month"));

        if (count($terminals) > 0) {
            foreach ($terminals as $key => $val) {
                $today += Lib::countTran($val['sn'], $val['table'], $todayDate, "d");
                $month += Lib::countTran($val['sn'], $val['table'], $monthDate, "m");
                $lastMonth += Lib::countTran($val['sn'], $val['table'], $lastMonthDate, "m");
            }
        }

        $this->success("首页数据", [
            "today" => $today,
            "month" => $month,
            "last_month" => $lastMonth,
        ]);
    }

    public function saveProductApply()
    {
        $productId = $this->request->post('product_id', 0);
        $type = $this->request->post('type');

        //        if (!$productId) {
        //            $this->error("产品ID不存在");
        //        }

        $addressId = 0;
        if ($type == 2) {
            $addressId = $this->request->post('address_id');

            if (!$addressId) {
                $this->error("缺少地址信息");
            }
        }

        $result = Tools::saveProductApply($productId, $type, $this->auth->id, $addressId);

        if ($result) {
            \app\data\controller\Apply::instance()->place_update_status($this->auth->id, $result);
            $this->success("申请成功！", $result);
        } else {
            $this->error("申请失败，请稍后再试");
        }
    }

    public function getProductList()
    {
        $this->success("产品列表", Lib::getProductList());
    }

    //保存身份证信息
    public function saveIdCard()
    {
        $front = $this->request->post('front');
        $back = $this->request->post('back');
        $name = $this->request->post('name');
        $idcard = $this->request->post('idcard');

        if (!$front || !$back) {
            $this->error("缺少图片");
        }

        if (!empty($idcard)) {
            $nums = User::where("idcards", $idcard)->where("status", "normal")->count();
            if ($nums > 0) {
                $this->error("该身份证号已被实名！");
            }
        }

        $card = new UserCard();
        $card->sale_id = $this->auth->id;
        $card->card_front = $front;
        $card->card_back = $back;
        $card->real_name = $name;
        $card->real_idcard = $idcard;
        $result = $card->save();

        if ($result) {
            $user = $this->auth->getUser();
            $user->is_verify = 1;
            if (!empty($idcard)) {
                $user->idcards = $idcard;
            }
            $user->save();
            $this->success("保存成功！");
        } else {
            $this->error("保存失败！");
        }
    }

    //相关协议
    public function getAgree()
    {
        $this->success("相关协议", [
            "about" => Config::get("site.about"),
            "user_agree" => Config::get("site.user_agree"),
            "register" => Config::get("site.register"),
            "contract" => config("contract"),
        ]);
    }

    //注册-推荐人
    public function getReferrer()
    {
        $type = $this->request->post('type');
        $id = $this->request->post('id');

        if (!$type || !$id) {
            $this->error("缺少参数!");
        }

        $info = User::where('id', $id)->field("id,nickname name")->find();

        $this->success("推荐人信息", ["data" => $info]);
    }

    public function test()
    {
        $url = $this->request->get('url');
        $wechat = config("wechat");
        $config = [
            'app_id' => $wechat["AppID"],
            'secret' => $wechat["AppSecret"],
            'response_type' => 'array'
        ];

        $app = Factory::officialAccount($config);
        $APIs = ["qrCode", "barCode", "scanQRCode"];
        $res = $app->jssdk->buildConfig($APIs, $debug = false, $beta = false, $json = true, [], $url);
        $this->success("公众号配置", json_decode($res, true));
    }

    //发送验证码
    public function sendSms()
    {
        $mobile = $this->request->post('mobile');
        $type = $this->request->post('type', 1);
        if ($type == 1) {
            $find = Db::name("user")->where(["mobile" => $mobile])->find();
            if ($find) {
                if ($find["status"] != "normal") {
                    $this->error("该账号禁止登录");
                } else {
                    if ($find["is_typs"] == 2) {
                        $this->error("该账号非内部人员，禁止登录");
                    }
                }
            } else {
                $this->error("用户不存在");
            }
        }
        if ($type == 3) {
            if ($this->auth->username == $mobile) {
                $this->error("请输入新手机号！");
            } else {
                $nums = Db::name("user")->where(["mobile" => $mobile, "status" => "normal"])->count();
                if ($nums > 0) {
                    $this->error("该手机号已注册！");
                }
            }
        }
        $code = Random::numeric(6);
        $result = sendSms(65, $code, $mobile);
        if ($result == "OK") {
            $this->success("发送成功！");
        } elseif ($result == "Failed") {
            $this->error("发送失败！");
        } elseif ($result == "NO") {
            $this->error("请稍后再试！");
        }
    }
}
